import {Server} from 'socket.io';
import {createServer} from 'http';

export default fromNodeMiddleware(() => {
    // 创建一个 HTTP 服务器实例
    const httpServer = createServer();

    // 创建一个 Socket.IO 服务器实例，并将其附加到 HTTP 服务器上
    const io = new Server(httpServer, {
        cors: {
            origin: "*",
        }
    });

    io.on('connection', (socket) => {
        console.log('客户端已连接：', socket.id);

        socket.on('offer', (offer) => {
            console.log('收到 offer:', offer);
            socket.broadcast.emit('offer', offer);
        });

        socket.on('answer', (answer) => {
            console.log('收到 answer:', answer);
            socket.broadcast.emit('answer', answer);
        });

        socket.on('ice-candidate', (candidate) => {
            console.log('收到 ICE 候选者:', candidate);
            socket.broadcast.emit('ice-candidate', candidate);
        });

        socket.on('disconnect', () => {
            console.log('客户端已断开连接：', socket.id);
        });
    });


    // 启动 HTTP 服务器并监听端口
    const PORT = 8560;
    httpServer.listen(PORT, () => {
        console.log(`服务器正在监听端口 ${PORT}`);
    });
})